import {useImmerState} from '../../hooks/useImmerState';
import {listLessonExchange, setLessonExchange} from '../../apis/course';
import useGlobal from '../../hooks/useGlobal';
import useDidMount from '../../hooks/useDidMount';
import {message} from 'antd';

const useExchangeModel = () => {
  const [state, setState] = useImmerState({
    list: []
  });

  const {state: globalState} = useGlobal();

  const getList = async () => {
    const res = await listLessonExchange(globalState.login?.token);
    if (res.code === 1) {
      setState(draft => {
        draft.list = res.data.list.map(item => ({...item, key: item.id}));
      });
    }
  };

  const resolve = async (record) => {
    const res = await setLessonExchange(globalState.login?.token, record.id, 1);
    if (res.code === 1) {
      setState(draft => {
        draft.list = draft.list.map(item =>
          item.id === record.id ? {...item, status: 1} : item
        );
      });
    } else {
      message.error(res.msg);
    }
  };

  const reject = async (record) => {
    const res = await setLessonExchange(globalState.login?.token, record.id, 0);
    if (res.code === 1) {
      setState(draft => {
        draft.list = draft.list.map(item =>
          item.id === record.id ? {...item, status: 0} : item
        );
      });
    } else {
      message.error(res.msg);
    }
  };

  const effect = {
    getList,
    resolve,
    reject
  };

  useDidMount(() => {
    getList();
  });

  return {
    state,
    effect
  };
};

export default useExchangeModel;